package com.yootk.action;

import com.yootk.action.abs.AbstractAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/pages/common/*")
public class UploadAction extends AbstractAction {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadAction.class);
    @PostMapping("upload")
    @ResponseBody
    public Object upload(String id, MultipartFile photo) throws Exception{
        Map<String,Object> map = new HashMap<>() ;
        map.put("id",id) ;
        map.put("getContentType",photo.getContentType()) ;
        map.put("getOriginalFilename",photo.getOriginalFilename()) ;
        map.put("getSize",photo.getSize()) ;
        map.put("saveFileName",this.save(photo)) ;
        return  map ;
    }
    @GetMapping("input")
    public String input() {
        return "/pages/common/input.jsp";
    }
    public String save(MultipartFile file) throws Exception{
        String fileName = UUID.randomUUID() + "." +  file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1) ;
        LOGGER.info("生成文件名称：{}", fileName);
        String filePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/upload/") + fileName ;
        LOGGER.info("文件存储路径：{}", filePath);
        file.transferTo(new File(filePath));
        return fileName ;
    }
}
